<!-- 购物车 -->
<template>
	<view class="cart pr" style="background: #F8F8FB;">
		<u-navbar :is-back="false" title="购物车">
		</u-navbar>
		<view class="cart_content">
			<view class="tip" v-if="!cart_group.length">
				<view class="x-c">
					<image :src="cart" />
				</view>
				<view class="name  x-c">购物车空空如也~</view>
			</view>
			<view class="cart_item">
				<swipe-action v-for="(cart, index) in cart_group" :key="cart.id" :index="index" @click.stop="click"
					:options="options" :show="cart.show" @open="open" btn-width="120" bgColor="#F8F8FB" btn_margin="24"
					:btn_radiousR="8">
					<view class="cart_card df" :class="{'change_card' : cart.checked}">
						<view class="cart_left x-f">
							<view class="left_check">
								<image class="select"
									:src="cart.checked == true? select_ico.seleted:select_ico.no_select"
									@tap.stop="selecting(cart,index)"></image>
							</view>
							<image :src="cart.pic_url" alt mode="aspectFit" class="cart_photo"
								@click.stop="goDetail(index)"></image>
						</view>
						<view class="cart_right fr">
							<view class="cart_title" @click.stop="goDetail(index)">
								<p>{{ cart.spu_name }}</p>
								<view class="x-f">
									<span>{{ cart.unit_points }}积分</span>
									<span>+¥ {{cart.unit_amount }}元</span>
								</view>
							</view>
							<view class="card_calculation fr">
								<number @reduce="reduce" @add="add" :index="index" :item="cart"></number>
							</view>
						</view>
					</view>
				</swipe-action>
			</view>
			<view class="love">
				<view class="title">猜你喜欢</view>
				<goods-list :goods_data="goods_data" @getId="getId"></goods-list>
			</view>
			<view class="pf x-bc card_bottom">
				<view class="y-start card_left">
					<view class="x-f">
						<image class="card_active" :src="count != 0 ? select_ico.seleted:select_ico.no_select">
						</image>
						<view>已选({{ count }})</view>
					</view>
					<view class="x-f money">
						<view class="">共计：{{sum}} <span>积分</span></view>
						<view class="">+¥{{money}} <span>元</span></view>
					</view>
				</view>
				<view class="card_right">
					<button class="swap_text" type="default" :disabled="count === 0 ? true : false"
						@click.stop="jump('/pages/order/index')" :class="count === 0 ? 'notClick': ''">
						立即兑换
					</button>
				</view>
			</view>
		</view>
		<template>
			<buttom-tabbar></buttom-tabbar>
		</template>
	</view>
</template>
<script>
	import {
		mapMutations,
		mapActions,
		mapState,
		mapGetters
	} from 'vuex';
	import mixins from '@/common/mixins.js';
	import number from './components/numberBox.vue'
	export default {
		mixins: [mixins],
		components: {
			number
		},
		data() {
			return {
				cart: this.imgUrl + 'cart.png',
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#FF5445',
					}
				}],
				value: 1,
				select_ico: {
					seleted: this.imgUrl + 'common_ic_12_selected.png',
					no_select: this.imgUrl + 'common_ic_12.png',
				},
				sum_list: [],
				btncount: 1, // 步进器值
				numbox: -1, //步进器下标
				selectGoods: [], // 选择购物车列表
				cartGoods: [], // 去重购物车列表
				goStatus: false, // 来这个页面
				actStatus: false, //  商品选择状态
			};
		},
		computed: {
			...mapState({
				cart_group: state => state.cart.cart_group,    // 购物车列表
				sum: state => state.cart.sum,				   // 总积分
				count: state => state.cart.count,			   // 已选数量
				selectGoodsS: state => state.cart.selectGoods, // 已选商品
				money: state => state.cart.money,			   // 总金额
				goods_data: state => state.goods.goodsLove,    // 商品数据
				order: state => state.order.order,			   // 订单列表
			})
		},
		onShow() {
            // 给所有购物车数据追加一个属性
			this.cart_group.forEach(item => {
				item.checked = false
			})
		},
		mounted() {
			this.selectGoods = this.selectGoodsS
			// 判断当购物车的内容为空时
			if(!this.cart_group.length) {
				this.$store.dispatch('cart/get_sum', 0)
				this.$store.dispatch('cart/get_money', 0)
			}
			// 当购物车的内容不为空时，且商品未选择
			if(!this.actStatus) {
				this.$store.dispatch('cart/get_sum', 0)
				this.$store.dispatch('cart/get_money', 0)
			}
			// 当加载页面时清除购物车选择状态
			this.cart_group.forEach(item=> {
				item.checked = false;
				this.$store.dispatch('cart/get_count', 0)
			})
			// 猜你喜欢
			this.get_goods();
		},
		methods: {
			// 猜你喜欢
			get_goods() {
			    this.$store.dispatch('goods/get_goodsLove', {
			    	page: 1,
			    	pagesize: 10,
			    	category_id: 0,
			    	orderby_type: 'number',
			    	orderby: 'asc',
			    })
			},
			// 获取商品id
			getId(e) {
				this.$store.dispatch('goods/get_detail', e)
			},
			// 减少商品数量
			reduce(item,index){
			// 获取商品数量
			let sale_count = this.cart_group[index].sale_count;
			// 获取第几个商品
			let cart = this.cart_group[index];
			// 只有商品数量大于等于2的时候才允许减少商品。
			if (sale_count >= 2) {
				cart.sale_count--;
				// 当商品数量大于等于2，且金额为零的情况下。
				// 进行积分减少 - 否则进行金额消减；
				if (cart.consume_amount == 0) {
					cart.consume_points = cart.consume_points - cart.points;
					cart.unit_amount = cart.consume_points - cart.points;
				} else {
					// 所需总金额 = 商品数量 * 商品单价积分 - 商品总积分  / 1000
					cart.consume_amount = ((cart.sale_count * cart.points) - cart.consume_points) / 1000
					cart.unit_amount = ((cart.sale_count * cart.points) - cart.consume_points) / 1000
				}
				// 构造传递后台的请求参数信息；
				let spu_id = item.spu_id.toString();
				let sku_id = item.sku_id.toString();
				let obj = {
					spu_id,
					sku_id,
					sale_count: cart.sale_count,
					consume_amount: cart.consume_amount,
					consume_points: item.consume_points
				}
				this.$api('memberhandleCart', obj)
			}
			if (sale_count == 1) {
				sale_count = 1;
			}
			this.sumTotal();
		},
		// 增加商品数量
		add(item, index) {
			// 获取商品数量
			let sale_count = this.cart_group[index].sale_count;
			// 获取第几个商品
			let cart = this.cart_group[index];
			// 增加商品数量
			cart.sale_count++;
			// 计算商品金额；
			cart.consume_amount = ((cart.sale_count * cart.points) - cart.consume_points) / 1000;
			cart.unit_amount = ((cart.sale_count * cart.points) - cart.consume_points) / 1000;
			let spu_id = item.spu_id.toString();
			let sku_id = item.sku_id.toString();
			// 构造传递后台的请求参数信息；
			let obj = {
				spu_id,
				sku_id,
				sale_count: cart.sale_count,
				consume_amount: cart.consume_amount,
				consume_points: item.consume_points
			}
			this.$api('memberhandleCart', obj)
            // 计算价格
			this.sumTotal();
		},
		// 订单跳转
		toOrder() {
			this.$Router.push({
				path: '/pages/order/index'
			})
		},
		jump(path, params) {
			// 添加信息到订单
			let orderArr = this.cart_group.filter(item=> {
				item.coupon_no = ''
				return item.checked == true;
			})
			this.$store.dispatch('order/get_order', orderArr)
			this.type = 'cart';
			this.$store.dispatch('order/get_type', this.type);
			// 添加订单成功 删除购物车的产品列表
			let arr = [];
			let pointList = [];
			let isAllEqual = false;
			let sellerId = '';
			let maxPoint = 0;
			this.selectGoods.map((item, index) => {
				arr.push(item.shop_id)
				pointList.push(item.points)
			})
			// 判断是否全等
			this.isAllEqual(arr)
			isAllEqual = this.isAllEqual(arr)
			if (isAllEqual) {
				sellerId = this.selectGoods[0].shop_id
			}
			// 查询最大值
			maxPoint = Math.max(...pointList)
			// 查询最大值
			let maxList = []
			this.selectGoods.map((item, index) => {
				arr.push(item.shop_id)
				maxList.push(item.consume_points)
			})
			let max = Math.max(...maxList)
			// 查询可用优惠券
			this.$api('ordercoupon', {
				shop_id: sellerId,
				max_points: maxPoint
			}).then(res => {
				let arr = res
				arr.data.map(item => {
					item.flag = false;
					item.use_end_time = this.time_data(item.use_end_time, 'f_date');
					item.use_start_time = this.time_data(item.use_start_time, 'f_date');
				})
				this.$store.dispatch('order/get_canUser', arr.data)
			})
			// 路由跳转 - 追加页面栈
			this.$Router.push({
				path: path,
				params: params
			})
		},
		isAllEqual(array) {
            // 检测数组中的元素是否满足条件
			if (array.length > 0) {
				return !array.some(function(value, index) {
					return value !== array[0];
				});
			} else {
				return true;
			}
		},
		//当商品被选中时
		selecting(item, index) {
			this.actStatus = true;
			this.cart_group[index].checked = !this.cart_group[index].checked
			this.sumTotal(index)
		},
		//计算价格
		sumTotal(index) {
			// 数量
			let count = 0;
			// 后台推送积分
			let sum = 0;
			// 支付金额
			let money = 0;
			// 商品信息
			let goods = [];
			// 金额列表
			let money_list = 0;
			// 所需总积分
			let integral = 0;
			/**
			 * 遍历购物车数组信息
			 * 如果checked 为真的情况下 进行数量累计
			 * 所需总积分 - 后台推送过来积分 = 所需要的积分
			 * 金额计算 = 所需要的积分 / 1000
			 */
			this.cart_group.map((item, index) => {
				if (item.checked) {
					// 当前的元素
					let cart = this.cart_group[index]
					// 数量
					count++
					// 后台推送过来的积分
					this.sum_list[index] = cart.consume_points;
					// 后台推送过来的金额
					money_list += cart.consume_amount * this.btncount;
					// 所需的总积分
					integral += cart.points * cart.sale_count - cart.consume_points;
					// 计算所需总积分
					sum += this.sum_list[index];
					// 计算所需总金额
					money = integral / 1000;
					// 将商品信息推送至订单信息中
					this.selectGoods.push(item)
				}
			})            
			// 购物车去重
			this.cartGoods = [...new Set(this.selectGoods)]
			// 保存信息到vuex
			this.$store.dispatch('cart/get_sum', sum)
			this.$store.dispatch('cart/get_count', count)
			this.$store.dispatch('order/get_sumInit', sum)
			this.$store.dispatch('cart/get_money', money)
			// 筛选已选商品
			let checkedGood = [];
			checkedGood = this.cartGoods.filter((item, index) => {
				return item.checked == true
			})
		},
		// 删除购物车
		click(index) {
			// 删除购物车
			let str = this.cart_group[index]
			this.$api('memberhandleCart', {
				spu_id: str.spu_id.toString(),
				sku_id: str.sku_id.toString(),
				sale_count: 0,
				consume_amount: str.consume_amount,
				consume_points: str.consume_points
			}).then(res => {
				let arr = res
				if (arr.status) {
					this.$tools.toast('商品删除成功')
					this.cart_group.splice(index, 1);
					this.sumTotal();
				}
			})
		},
		// 如果打开一个的时候，不需要关闭其他，则无需实现本方法
		open(index) {
			// 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
			// 原本为'false'，再次设置为'false'会无效
			this.cart_group[index].show = true;
			this.cart_group.map((val, idx) => {
				if (index != idx) this.cart_group[idx].show = false;
			})
		},
		// 跳转至商品详情
		goDetail(index) {
			let that = this;
			let good = this.cart_group[index];
			let obj = {
				"spu_id": good.spu_id.toString(),
				"sku_id": good.sku_id.toString(),
			}
			that.$api('giftinfo', obj).then(res => {
				let goods = res.data;
				that.$store.dispatch('goods/get_goodsInfo', goods)
			})
			that.$store.dispatch('goods/get_detail', good)
			that.$Router.push({
				path: '/pages/goods/detail/index',
			})
		}
	},
};
</script>
<style scoped lang='scss'>
	@import "./index.scss";
</style>

<style scoped>
	.u-swipe-action /deep/ .movable-area {
		margin-top: 24rpx !important;
		border-radius: 16rpx;
	}
</style>
